package framework.utils;

import java.security.MessageDigest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.crypto.hash.SimpleHash;

import framework.common.UserSecurity;

public class MD5Utils {
	static Log log = LogFactory.getLog(MD5Utils.class);
	static final String MD5 = "MD5";

	/**
	 * 将字符串使用MD5加密
	 */
	public static String encode(String in) {
		MessageDigest md5 = null;

		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return in;
		}

		char[] charArray = in.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];

		byte[] md5ByteArray = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5ByteArray.length; i++) {
			int val = ((int) md5ByteArray[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");

			hexValue.append(Integer.toHexString(val));
		}

		return hexValue.toString();
	}

	/**
	 * 将字符串使用MD5盐值加密
	 * 
	 * @param in
	 *            加密字符串
	 * @param salt
	 *            盐值
	 * @return String md5
	 */
	public static String encodeUseSalt(String password, String userId) {

		SimpleHash hash = new SimpleHash(MD5, password, UserSecurity.getCredentialsSalt(userId), 1);
		String encodedPassword = hash.toHex();
		return encodedPassword;
	}

}
